#include <stdio.h>
#include <string.h>

/* 将一个字符串逆序,使用递归 */
char *reverse_recurion(char *str)
{
    if (str == NULL)
        return NULL;
    int len = strlen(str);
    if( len > 1 )
    {
        char ctemp =str[0] ;
        str[0] = str[len-1];
        str[len-1] = '\0';
        reverse_recurion(str+1);
        str[len-1] =ctemp;
    }
    return str;
}

char *reverse(char *str)
{
    if (str == NULL)
        return NULL;

    int count = 0;
    int count_div = 0;
    char *begin = str;
    char temp;

    char *p_begin = str;
    char *p_end = str;
    while(*str != '\0')
    {
        count++;
        str++;
    }
    p_end = --str;      /* 回退一个使p_end指向最后一个字符 */
    count_div = count / 2;

    while(count_div > 0)
    {
        temp = * p_begin;
        *p_begin = *p_end;
        *p_end = temp;
        p_begin++;
        p_end--;
        count_div--;
    }

    return begin;
}

char *reverse2(char *str)       /* 上面使用长度计算终止完全没有必要，直接用指针值比较就ok了 */
{
    char *p_begin = str;
    char *p_end = str;
    while(*str++)
        p_end++;
    p_end--;
    while(p_end > p_begin)
    {
        char temp = *p_begin;
        *p_begin++ = *p_end;
        *p_end-- = temp;
    }
    return str;   
}

/* 对指针start和end之间的所有字符逆序 */
void ReverseWord(char* start, char* end)
{
    while(start < end)
    {
        char temp = *start ;
        *start++ = *end ;
        *end-- = temp ;
    }
}

/* 将句子按单词逆序 */
char* ReverseSentence(char* str)
{
    // 这两个指针用来确定一个单词的首尾边界
    char* p_start = str ;       // 指向单词的首字符
    char* p_end = str ;         // 指向空格或者 '\0'

    while(*p_end != '\0')
    {
        if (*p_end == ' ')
        {
            ReverseWord(p_start, p_end - 1) ;
            p_end++ ;           // 指向下一个单词首字符
            p_start = p_end ;
        }
        else
            p_end++ ;
    }

    ReverseWord(p_start, p_end - 1) ;   // 对最后一个单词逆序
    ReverseWord(str, p_end - 1) ;       // 对整个句子逆序

    return str ;
}
int main()
{

    char str[] ="abcdefghijklABCDEFGHIJL";
    char sentence[] = "This is a sentence";
    printf("Befor str = %s\n", str);
    reverse2(str);
    printf("After str = %s\n", str);

    printf("Befor sentence = %s\n", sentence);
    ReverseSentence(sentence);
    printf("After sentence = %s\n", sentence);
    
    return 0;
}
